# -*- coding: utf-8 -*-
import os

import requests
import json

import sys


class DoubanMovie(object):
    def __init__(self):
        self.refer_url = 'https://m.douban.com/movie/'
        self.url = 'https://m.douban.com/rexxar/api/v2/subject_collection/movie_showing/items?os=windows&callback=jsonp1&start=0&count=8&loc_id=108288&_=0'
        self.filename = 'ext/E2_douban_movie.json'

    def get_data(self):
        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        _ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        _ua_file = {'pc': '{0}Utils/{1}'.format(_path, _ei.ExtractInfo.ua_file['pc'])}
        _user_agent = _ei.ExtractInfo.get_useragent(file=_ua_file)
        _s = requests.session()
        _s.get(self.refer_url, headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'},
               verify=False)
        _response = requests.get(self.url, headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'},
                                 verify=False)
        # TODO 400

        return _response.content.decode()

    def parse_data(self, data):
        print(data)
        _movie_list = json.loads(data)['subject_collection_items']
        _data_list = []
        for _movie in _movie_list:
            _temp = {}
            _temp['title'] = _movie['title']
            _temp['url'] = _movie['url']
            _data_list.append(_temp)

        return _data_list

    def save_data(self, data_list):
        with open(self.filename, mode='w', encoding='utf-8')as f:
            for _data in data_list:
                _str_data = json.dumps(_data, ensure_ascii=False) + ",\n"
                f.write(_str_data)

    def run(self):
        _data = self.get_data()
        _data_list = self.parse_data(_data)
        self.save_data(_data_list)


def main():
    dbm = DoubanMovie()
    dbm.run()


if __name__ == '__main__':
    main()
